/**
 * 
 */
package com.yinhai.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.cmcc.groupcontacts.MainApp;
import com.lz.util.Utils;
import com.yinhai.adapter.MSGListSwipeAdapter;
import com.yinhai.constant.ChatConstant;
import com.yinhai.model.IMList;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.service.MsgServiceImpl;
import com.yinhai.util.CMUtil;
import com.yinhai.util.Util;
import com.yinhai.view.PullToSwipeListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Juyon
 * 
 */
public class MsgFragmentnew extends Fragment {
    
    public static Map<String, Intent> mapChatService = new HashMap<String, Intent>();
    
    private PullToSwipeListView listView;
    
    private MSGListSwipeAdapter adapter;
    
    private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    
//    private TextView rb_msg_radio_im, rb_msg_radio_sms;
    
    // private View topProgressView;// bottomProgressView;
    private ImageView btn_add;
    
    private View im_msg_status;
    
    private TextView tv_msg_tip;
    
    private PopupWindow imPopWindow;// 消息弹出框
    
    private List<Map<String, Object>> impPopList = new ArrayList<Map<String, Object>>();// 消息弹出框数据
    
    private SimpleAdapter imSimpleAdapter;
    
    private Context context;
    
    private AQuery aq;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_msg, null);
        aq = new AQuery(getActivity(), view);
        aq.id(R.id.common_ad).visible();
        aq.id(R.id.common_ad).clicked(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                aq.id(R.id.number).gone();
                Intent it = new Intent(getActivity(), CommonADContentActivity.class);
                startActivity(it);
            }
        });
        aq.id(R.id.msg_lst1).getListView().setVisibility(View.GONE);
        
        try {
            
            context = this.getActivity();
            btn_add = (ImageView)view.findViewById(R.id.btn_add);
            btn_add.setImageResource(R.drawable.nav_add);
            btn_add.setVisibility(View.GONE);
            btn_add.setClickable(true);
            im_msg_status = (View)view.findViewById(R.id.im_msg_status);
            tv_msg_tip = (TextView)view.findViewById(R.id.msg_tip);
            
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.im.login");
            intentFilter.addAction("com.im.message");
            intentFilter.addAction("com.im.sendmessage");
            intentFilter.addAction("com.im.delmessage");
            intentFilter.addAction("com.im.commonad");
            intentFilter.addAction("com.im.login.success");
            intentFilter.addAction("com.im.login.error");
            intentFilter.addAction("com.im.NetstateReceiver");
            intentFilter.addAction("com.im.NetstateReceiverTrue");
            getActivity().registerReceiver(receiver, intentFilter);
            
            listView = (PullToSwipeListView)view.findViewById(R.id.msg_lst);
            listView.setVisibility(View.VISIBLE);
            adapter = new MSGListSwipeAdapter(getActivity(), data, listView.getRightViewWidth());
            
            adapter.setOnRightItemClickListener(new MSGListSwipeAdapter.onRightItemClickListener() {
                
                @Override
                public void onRightItemClick(View v, int position) {
                    try {
                        
                        final Map<String, Object> valMap = (Map<String, Object>)adapter.getItem(position);
                        String id = valMap.get("threadId").toString();
                        new MsgServiceImpl(getActivity()).updateShowStatusByIM_Id(id);
                        listView.deleteItem(listView.getChildAt(position));
                        data.remove(position);
                        adapter.notifyDataSetChanged();
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            
            listView.setAdapter(adapter);
            
//            rb_msg_radio_im = (TextView)view.findViewById(R.id.msg_radio_im);
//            rb_msg_radio_sms = (TextView)view.findViewById(R.id.msg_radio_sms);
            
            // 消息页面
//            rb_msg_radio_sms.setBackgroundResource(R.drawable.msg_right_radio_bg_unsel);
//            rb_msg_radio_im.setBackgroundResource(R.drawable.msg_left_radio_bg_sel);
//            rb_msg_radio_sms.setTextColor(Color.parseColor("#0789da"));
//            rb_msg_radio_im.setTextColor(Color.parseColor("#ffffff"));
            
            tv_msg_tip.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (MainApp.isIMConnecteStatus == 2) {
                        im_msg_status.setVisibility(View.GONE);
                        btn_add.setVisibility(View.VISIBLE);
                        return;
                    }
                    if (MainApp.isIMConnecteStatus == 1) {
                        tv_msg_tip.setText("正在登录即时通讯");
                        Util.showMsg(getActivity(), "正在登录即时通讯");
                        return;
                    }
                    ContactUserServiceImpl cuContactUserServiceImpl = new ContactUserServiceImpl(getActivity());
                    if (cuContactUserServiceImpl.isUpdatedOnlineContactUser()) {
                        CMUtil.getInstance(getActivity()).doLogin();
                        tv_msg_tip.setText("正在登录即时通讯");
                    } else {
                    	Toast.makeText(context, "集团通讯录未同步，请先同步集团通讯录!", Toast.LENGTH_LONG).show();
//                        new AlertDialog.Builder(getActivity()).setTitle("是否同步通讯录数据")
//                        // .setView("")
//                            .setNeutralButton("取消", new DialogInterface.OnClickListener() {
//                                
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    
//                                }
//                            })
//                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    LoginConfig log = LoginConfigUtil.getConfig(context);
//                                    ContactUserServiceImpl c = new ContactUserServiceImpl(context);
//                                    c.initOnlineContact(log.getUsername());
//                                }
//                            })
//                            .show();
                    }
                }
            });
            
            // 点击弹出框，还是跳转到编辑短信页面
            view.findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    
                    try {
                        
                        // if (!imPopWindow.isShowing()) {
                        // imPopWindow.showAtLocation(getActivity().findViewById(R.id.btn_add), Gravity.TOP, 100, 110);
                        // } else {
                        // imPopWindow.dismiss();
                        // }
                        Intent intent = new Intent(getActivity(), ContactActivity.class);
                        intent.putExtra("userType", 3);
                        intent.putExtra("isMutiCheck", false);
                        startActivity(intent);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            
            // 点击跳转
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                
                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
                    try {
                        
                        // 获取传入的数据
                        Map<String, Object> valMap = (Map<String, Object>)adapter.getItem(position);
                        if ("-1".equals(valMap.get("threadId"))) {
                            Intent intent = new Intent(getActivity(), ChatGroupActivity.class);
                            startActivity(intent);
                            return;
                        }
                        valMap.put("number", 0);
                        view.findViewById(R.id.number).setVisibility(View.GONE);
                        IMList imList = (IMList)valMap.get("data");
                        Intent intent = new Intent(getActivity(), ChatActivity.class);
                        intent.putExtra("receID", imList.getRecId());
                        intent.putExtra("receName", imList.getRecName());
                        
                        if (imList.isGroup.equals("0")) {
                            // 1:一对一；2：部门；3：群组
                            intent.putExtra("type", 1);
                            ChatConstant.CURRENT_CHAT = "1";
                            ChatConstant.CURRENT_CHART_ID = imList.getRecId();
                        } else {
                            intent.putExtra("type", 3);
                            ChatConstant.CURRENT_CHAT = "2";
                            ChatConstant.CURRENT_CHART_ID = imList.getRecId();
                            intent.putExtra("groupId", imList.getRecId());
                            intent.putExtra("groupName", imList.getRecName());
                        }
                        startActivity(intent);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        if (MainApp.isIMConnecteStatus == 2) {
            im_msg_status.setVisibility(View.GONE);
            btn_add.setVisibility(View.VISIBLE);
            reLoginHandler.sendEmptyMessage(1);
        } else if (MainApp.isIMConnecteStatus == 1) {
            tv_msg_tip.setText("正在登录即时通讯");
            im_msg_status.setVisibility(View.VISIBLE);
            btn_add.setVisibility(View.GONE);
        } else {
            tv_msg_tip.setText("点击登录");
            im_msg_status.setVisibility(View.VISIBLE);
            btn_add.setVisibility(View.GONE);
        }
        
    }
    
    private void findIMData() {
        try {
            List<IMList> list = new MsgServiceImpl(getActivity()).findOwnMsgList();
            for (IMList imList : list) {
                Map<String, Object> map = new HashMap<String, Object>();
                if (imList.isGroup.equals("0")) {
                    map.put("img", R.drawable.tel_photo);
                } else {
                    map.put("img", R.drawable.groupbook_folder);
                }
                map.put("threadId", imList.getId() + "");
                map.put("name", imList.getRecName());
                map.put("content", imList.getContent());
                map.put("number", imList.getUnreadNumber() + "");
                map.put("data", imList);
                data.add(map);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("img", R.drawable.tel_photo);
            map.put("threadId", "-1");
            map.put("name", "群聊");
            map.put("content", "发起群聊");
            data.add(0, map);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals("com.im.sendmessage") || intent.getAction().equals("com.im.message")) {
                    
                    HandlerThread myThread = new HandlerThread("myHandlerThread");
                    myThread.start();
                    MyHandler handler = new MyHandler(myThread.getLooper());
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                    
                } else if (intent.getAction().equals("com.im.delmessage")) {
                    data.clear();
                    adapter.notifyDataSetChanged();
                    findIMData();
                } else if (intent.getAction().equals("com.im.commonad")) {
                    aq.id(R.id.number).text(intent.getIntExtra("ad_num", 0) + "").visible();
                    /*
                     * if (radioCheckID == R.id.msg_radio_im) { }
                     */
                } else if (intent.getAction().equals("com.im.NetstateReceiver")) {
                    tv_msg_tip.setText("请检查网络!");
                } else if (intent.getAction().equals("com.im.NetstateReceiverTrue")) {
                    tv_msg_tip.setText("正在自动登录，请稍后...");
                } else if (intent.getAction().equals("com.im.login.success")) {
                    reLoginHandler.sendEmptyMessage(2);
                } else if (intent.getAction().equals("com.im.login.error")) {
                    reLoginHandler.sendEmptyMessage(3);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    };
    
    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(receiver);
        super.onDestroy();
    }
    
    // 重新加载消息页面
    class SendMessageHandler extends Handler {
        
        public SendMessageHandler(Looper looper) {
            super(looper);
        }
        
        @Override
        public void handleMessage(Message msg) {
            
            try {
                
                super.handleMessage(msg);
                if (msg.what == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        
                        @Override
                        public void run() {
                            data.clear();
                            
                            adapter.notifyDataSetChanged();
                            // String sound = Utils.getSound(context);
                            if (Utils.getSound(context)) {
                                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), notification);
                                r.play();
                            } else if (!Utils.getSound(context)) {
                                Vibrator vibrator = (Vibrator)getActivity().getSystemService(Activity.VIBRATOR_SERVICE);
                                long[] pattern = {0, 50, 400, 30};
                                vibrator.vibrate(pattern, -1);
                            }
                            findIMData();
                            
                        }
                    });
                    
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    }
    
    /**
     * // 收到消息，更新会话列表
     * 
     * @author Administrator
     *
     */
    
    class MyHandler extends Handler {
        
        public MyHandler(Looper looper) {
            super(looper);
        }
        
        @Override
        public void handleMessage(Message msg) {
            try {
                
                super.handleMessage(msg);
                if (msg.what == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        
                        @Override
                        public void run() {
                            data.clear();
                            adapter.notifyDataSetChanged();
                            if (Utils.getSound(context)) {
                                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), notification);
                                r.play();
                            } else if (!Utils.getSound(context)) {
                                Vibrator vibrator = (Vibrator)getActivity().getSystemService(Activity.VIBRATOR_SERVICE);
                                long[] pattern = {0, 50, 400, 30};
                                vibrator.vibrate(pattern, -1);
                            }
                            findIMData();
                            
                        }
                    });
                    
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 已登录、更新会话界面
     * 
     * @author Administrator
     *
     */
    private Handler reLoginHandler = new Handler() {
        
        @Override
        public void handleMessage(Message msg) {
            try {
                
                super.handleMessage(msg);
                if (msg.what == 1) {
                    
                    data.clear();
                    findIMData();
                    // impPopList.clear();
                    // if (impPopList.isEmpty()) {
                    // Map<String, Object> item = new HashMap<String, Object>();
                    // item.put("title", "发起群聊");
                    // item.put("type", "0");
                    // impPopList.add(item);
                    //
                    // // 获取所有的群组
                    // ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(getActivity());
                    // List<ContactGroup> contactGroups = contactUserService.findGroup(null);
                    // for (ContactGroup contactGroup : contactGroups) {
                    // Map<String, Object> map = new HashMap<String, Object>();
                    // map.put("title", contactGroup.getName());
                    // map.put("type", 1);
                    // map.put("data", contactGroup);
                    // impPopList.add(map);
                    // }
                    //
                    // imSimpleAdapter =
                    // new SimpleAdapter(getActivity(), impPopList, R.layout.popupwindow_im_list_item,
                    // new String[] {"title"}, new int[] {R.id.title});
                    // View popView = getActivity().getLayoutInflater().inflate(R.layout.popwindow_im_add, null);
                    // ListView imPopListView = (ListView)popView.findViewById(R.id.im_group);
                    //
                    // imPopListView.setAdapter(imSimpleAdapter);
                    // imPopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    //
                    // @Override
                    // public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // if (imPopWindow != null) {
                    // imPopWindow.dismiss();
                    // }
                    // Map<String, Object> item = impPopList.get(arg2);
                    // String type = item.get("type").toString();
                    // if (type.equals("1")) {
                    // Intent intent = new Intent(getActivity(), ContactGroupAcitivty.class);
                    // intent.putExtra("groupID", ((ContactGroup)item.get("data")).getGroupId());
                    // startActivity(intent);
                    // } else {
                    // Intent intent = new Intent(getActivity(), ChatGroupActivity.class);
                    // startActivity(intent);
                    // }
                    // }
                    // });
                    // imPopWindow = new PopupWindow(popView, 300, LayoutParams.WRAP_CONTENT);
                    // imPopWindow.setFocusable(true);
                    //
                    // imPopWindow.setBackgroundDrawable(getActivity().getResources()
                    // .getDrawable(R.drawable.dial_dialog_bgup));
                    // imPopWindow.setOutsideTouchable(true);
                    // imPopWindow.update();
                    // }
                    
                } else if (msg.what == 2) {
                    if (MainApp.isIMConnecteStatus == 2) {
                        im_msg_status.setVisibility(View.GONE);
                        if (btn_add.getVisibility() != View.VISIBLE) {
                            btn_add.setVisibility(View.VISIBLE);
                        }
                        reLoginHandler.sendEmptyMessage(1);
                    } else {
                        im_msg_status.setVisibility(View.VISIBLE);
                        tv_msg_tip.setText("点击登录");
                        if (btn_add.getVisibility() == View.VISIBLE) {
                            btn_add.setVisibility(View.GONE);
                        }
                    }
                } else if (msg.what == 3) {
                    tv_msg_tip.setText("登录失败，请稍后重试.....");
                    im_msg_status.setVisibility(View.VISIBLE);
                    if (btn_add.getVisibility() == View.VISIBLE) {
                        btn_add.setVisibility(View.GONE);
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    };
    
    /**
     * 当没有网路的时候设置网路
     */
    private void loginin() {
        AlertDialog.Builder adg = new AlertDialog.Builder(context);
        adg.setTitle("网络错误:");
        adg.setMessage("是否手动设置网络？");
        adg.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                NetWorkStatus();
            }
        });
        adg.setNegativeButton("取消", null);
        adg.show();
    }
    
    private void NetWorkStatus() {
        startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
        
    }
    
    /**
     * 检查网路是否可用
     * 
     * @param context
     * @return
     */
    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
        }
        return false;
    }
    
}
